package com.auto.autoapp.ui.index

import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.auto.autoapp.base.BaseFragment
import com.auto.autoapp.databinding.FragmentIndexBinding
import com.auto.autoapp.services.FloatingWindowService
import com.auto.autoapp.ui.activity.CmdSetActivity
import com.auto.autoapp.widgets.SimpleToolbar
import com.ven.assists.AssistsCore

class IndexFragment : BaseFragment() {


    companion object Companion {
        fun newInstance(): IndexFragment {
            return IndexFragment()
        }
    }

    private var _binding: FragmentIndexBinding? = null

    private val binding get() = _binding!!
    override fun onInit() {
        val indexViewModel =
            ViewModelProvider(this)[IndexViewModel::class.java]
        initView()
    }

    override fun configToolbar(toolbar: SimpleToolbar) {
        toolbar.hideBack()
        toolbar.setTitle("首页")
    }

    override fun provideView(): View {
        _binding = FragmentIndexBinding.inflate(layoutInflater, null, false)
        return binding.root
    }


    fun initView() {
        // 初始化权限状态显示
        initPermissionStatusViews()
        binding.btnFloatingWindow.setOnClickListener {
            toggleFloatingWindow()
        }
        binding.btnCmdTest.setOnClickListener {
            if (AssistsCore.isAccessibilityServiceEnabled()) {
                openFloatingWindow()
                startActivity(Intent(requireContext(), CmdSetActivity::class.java))
            } else {
                AssistsCore.openAccessibilitySetting()
            }
        }
    }

    /**
     * 初始化权限状态显示视图
     */
    private fun initPermissionStatusViews() {
        // 设置无障碍服务设置按钮点击事件
        binding.btnAccessibilitySettings.setOnClickListener {
            openAccessibilitySettings()
        }

        // 设置悬浮窗权限设置按钮点击事件
        binding.btnOverlayPermissionSettings.setOnClickListener {
            openOverlayPermissionSettings()
        }

        // 初始更新状态
        updatePermissionStatus()
    }

    /**
     * 更新所有权限状态
     */
    private fun updatePermissionStatus() {
        updateAccessibilityServiceStatus()
        updateOverlayPermissionStatus()
    }

    /**
     * 打开无障碍服务设置页面
     */
    private fun openAccessibilitySettings() {
        AssistsCore.openAccessibilitySetting()
        Toast.makeText(requireContext(), "请在设置中开启无障碍服务", Toast.LENGTH_SHORT).show()
    }

    /**
     * 打开悬浮窗权限设置页面
     */
    private fun openOverlayPermissionSettings() {
        val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
        intent.data = android.net.Uri.parse("package:${requireContext().packageName}")
        startActivity(intent)
        Toast.makeText(requireContext(), "请在设置中授予悬浮窗权限", Toast.LENGTH_SHORT).show()
    }

    /**
     * 检查无障碍服务状态并导航到设置页面（如果未启用）
     * @return true 如果无障碍服务已启用，false 如果未启用并已跳转到设置页面
     */
    private fun checkAccessibilityServiceAndNavigate(): Boolean {
        return if (AssistsCore.isAccessibilityServiceEnabled()) {
            true
        } else {
            Toast.makeText(requireContext(), "请先开启无障碍服务", Toast.LENGTH_SHORT).show()
            AssistsCore.openAccessibilitySetting()
            false
        }
    }

    /**
     * 更新无障碍服务状态显示
     */
    private fun updateAccessibilityServiceStatus() {
        val isEnabled = AssistsCore.isAccessibilityServiceEnabled()
        val statusText = if (isEnabled) {
            "已开启"
        } else {
            "未开启"
        }
        binding.tvAccessibilityStatus.text = statusText
        binding.tvAccessibilityStatus.setTextColor(
            if (isEnabled) {
                resources.getColor(android.R.color.holo_green_dark, null)
            } else {
                resources.getColor(android.R.color.holo_red_dark, null)
            }
        )

        // 根据状态显示或隐藏设置按钮
        binding.btnAccessibilitySettings.visibility = if (isEnabled) View.GONE else View.VISIBLE
    }

    /**
     * 更新悬浮窗权限状态显示
     */
    private fun updateOverlayPermissionStatus() {
        val hasPermission = Settings.canDrawOverlays(requireContext())
        val statusText = if (hasPermission) {
            "已授予"
        } else {
            "未授予"
        }
        binding.tvFloatingStatus.text = statusText
        binding.tvFloatingStatus.setTextColor(
            if (hasPermission) {
                resources.getColor(android.R.color.holo_green_dark, null)
            } else {
                resources.getColor(android.R.color.holo_red_dark, null)
            }
        )

        // 根据权限状态显示或隐藏设置按钮
        binding.btnOverlayPermissionSettings.visibility =
            if (hasPermission) View.GONE else View.VISIBLE
    }

    /**
     * 更新悬浮窗服务状态显示
     */
    private fun updateFloatingWindowStatus() {
        val isFloatingWindowActive = FloatingWindowService.getInstance() == null
        val statusText = if (isFloatingWindowActive) {
            "悬浮窗状态：❌ 未开启"
        } else {
            "悬浮窗状态：✅ 已开启"
        }

        // 更新按钮文本
        binding.btnFloatingWindow.text = if (isFloatingWindowActive) {
            "开启悬浮窗"
        } else {
            "关闭悬浮窗"
        }
    }

    private fun openFloatingWindow() {
        if (!Settings.canDrawOverlays(requireContext())) {
            return
        }

        val floatingService = FloatingWindowService.getInstance()
        if (floatingService != null) {
            return
        } else {
            // 启动悬浮窗服务
            val intent = Intent(requireContext(), FloatingWindowService::class.java)
            intent.action = "SHOW_FLOATING_WINDOW"
            requireContext().startService(intent)
        }


    }

    /**
     * 切换悬浮窗显示状态
     */
    private fun toggleFloatingWindow() {
        if (!Settings.canDrawOverlays(requireContext())) {
            // 请求悬浮窗权限
            val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
            intent.data = android.net.Uri.parse("package:${requireContext().packageName}")
            startActivityForResult(intent, 1001)
            Toast.makeText(requireContext(), "请先授予悬浮窗权限", Toast.LENGTH_SHORT).show()
            return
        }

        val floatingService = FloatingWindowService.getInstance()
        if (floatingService != null) {
            // 关闭悬浮窗服务
            val intent = Intent(requireContext(), FloatingWindowService::class.java)
            intent.action = "HIDE_FLOATING_WINDOW"
            requireContext().startService(intent)
            Toast.makeText(requireContext(), "悬浮窗已关闭", Toast.LENGTH_SHORT).show()
        } else {
            // 启动悬浮窗服务
            val intent = Intent(requireContext(), FloatingWindowService::class.java)
            intent.action = "SHOW_FLOATING_WINDOW"
            requireContext().startService(intent)
            Toast.makeText(requireContext(), "悬浮窗已开启，可以监控执行日志", Toast.LENGTH_SHORT)
                .show()
        }

        // 更新状态显示
        updateFloatingWindowStatus()
    }

    override fun onResume() {
        super.onResume()
        // 每次回到页面时更新权限状态
        if (_binding != null) {
            updatePermissionStatus()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        Log.e("TAG", "onDestroyView: ")
        _binding = null
    }
}